package 并发编程16.消息发送测试2;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author idea
 * @data 2019/2/10
 */
public class MyDelayTask implements Delayed {

    private String name;
    private long start = System.currentTimeMillis();
    private long time;

    public MyDelayTask(String name, long time) {
        this.name = name;
        this.time = time;
    }

    /**
     * 获取延迟时间
     *
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert((start + time) - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 用于延迟队列排序 返回值>0则在队列前边
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        MyDelayTask o1= (MyDelayTask) o;
        return (int) (this.getDelay(TimeUnit.MILLISECONDS)-o.getDelay(TimeUnit.MILLISECONDS));
    }

    @Override
    public String toString() {
        return "MyDelayTask{" +
                "name='" + name + '\'' +
                ", start=" + start +
                ", time=" + time +
                '}';
    }
}
